﻿using System;
using System.Configuration;
using System.Drawing;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using Xenta.Utils;

namespace IisHost.UI
{
    public partial class PasswordControl : UserControl
    {
        public void BindData()
        {
            lblMessage.Visible = false;
        }

        protected void OnCommand(object sender, CommandEventArgs e)
        {
            lblMessage.Visible = false;

            switch(e.CommandName)
            {
                case "Change":
                    {
                        string password = txtPassword.Text.Trim();
                        if(!String.IsNullOrWhiteSpace(password))
                        {
                            string passwordHash = CryptoUtility.SHA1Hash(password)
                                .ToHexString();
                            try
                            {
                                var cfg = WebConfigurationManager.OpenWebConfiguration("~");

                                if(cfg.AppSettings.Settings["Password"] == null)
                                    cfg.AppSettings.Settings.Add("Password", passwordHash);
                                else
                                    cfg.AppSettings.Settings["Password"].Value = passwordHash;
                                cfg.Save(ConfigurationSaveMode.Modified);

                                lblMessage.ForeColor = Color.Green;
                                lblMessage.Text = "Operation completed successfully.";
                            }
                            catch(Exception ex)
                            {
                                lblMessage.ForeColor = Color.Red;
                                lblMessage.Text = ex.Message;
                            }
                            lblMessage.Visible = true;
                        }
                    }
                    break;
            }
        }
    }
}